import {reqShopCart,reqDeleteCartById,reqUpdateCheckedById} from "@/api";
const state={
    carList:[]
}
const mutations={
    GETCARLIST(state,carList){
       state.carList=carList
    }
}
const actions={
    //获取购物车列表
   async getCarList({commit}){
     let result=await reqShopCart()
       if (result.code==200){
           commit('GETCARLIST',result.data)
       }
    },
    //删除购物车某一个产品
    async deleteCartList({commit},skuId){
      let result= await reqDeleteCartById(skuId)
        if (result.code==200){
            return 'ok'
        }else {
            return Promise.reject(new Error('fail'))
        }
    },
    //修改购物车某一个产品选中状态
    async updateCheckedById({coommit},{skuId,isChecked}){
     let result= await reqUpdateCheckedById(skuId,isChecked)
        if (result.code==200){
            return 'ok'
        }else {
            return Promise.reject(new Error('fail'))
        }
    },
    //删除所有选中的商品
    async deleteAllCheckedCart({dispatch,getters}){
       //context:可以理解为小仓库
        //获取getters中购物车全部的商品
        let PromiseAll=[]
        getters.cartList.cartInfoList.forEach(item=>{
           let promise=item.isChecked==1?dispatch('deleteCartList',item.skuId):''
            //将每次返回的promise添加到数组中
            PromiseAll.push(promise)
        })
        //如果都成功 返回为true
        return Promise.all(PromiseAll)
    },
    //修改全选按钮状态
    async updateAllCartChecked({dispatch,state},isChecked){
        let PromiseAll=[]
         state.carList[0].cartInfoList.forEach(item=>{
        let promise = dispatch('updateCheckedById',{skuId:item.skuId,isChecked:isChecked})
             PromiseAll.push(promise)
         })
         return Promise.all(PromiseAll)
    }
}
const getters={
    cartList(state){
        return state.carList[0]||{}
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}
